Chart for WPF and Silverlight > Chart Features > Data Binding > Observable Collection |
WPF and Silverlight have a special generic collection class ObservableCollection which provides notification about updating such as when items get added, removed, or when the entire list is refreshed. If an instance of this class is used as a data source for the chart, the chart automatically reflects the changes that were made in the collection.
In code, add the System.Collections.ObjectModel namespace to your page (as well as C1.WPF.C1Chart or C1.Silverlight.Chart). This includes the ObservableCollection.
C# |
Copy Code
|
---|---|
using System.Collections.ObjectModel; using C1.WPF.C1Chart; //OR using C1.Silverlight.Chart; |
Then declare an ObservableCollection of type Point. This will be our chart data source:
C# |
Copy Code
|
---|---|
ObservableCollection<Point> points = new ObservableCollection<Point>();
|
Clear all preset chart data (if some exists) and then fill the points collection with some dummy values.
C# |
Copy Code
|
---|---|
//Clear chart data c1Chart1.Data.Children.Clear(); //Create dummy data points.Add(new Point(0, 20)); points.Add(new Point(1, 22)); points.Add(new Point(2, 19)); points.Add(new Point(3, 24)); points.Add(new Point(4, 29)); points.Add(new Point(5, 7)); points.Add(new Point(6, 12)); points.Add(new Point(7, 15)); |
Next, create a XYDataSeries bound to this collection and add it to the chart.
C# |
Copy Code
|
---|---|
//Setup C1Chart data series XYDataSeries ds = new XYDataSeries(); ds.Label = "Series 1"; //Bind data series to collection ds.ItemsSource = points; //Important to set binding when using ItemsSource ds.ValueBinding = new Binding("Y"); ds.XValueBinding = new Binding("X"); //Add data series to chart c1Chart1.Data.Children.Add(ds); |
You can bind the collection of points directly to the ItemsSource of the data series. It’s important to also specify the ValueBinding (Y) and XValueBinding to the X and Y fields of the Point object. Just like if this was your custom business object you’d have to bind the data series values to the desired field. Then add the data series to the chart’s Data collection. You could easily add multiple data series following this approach.